package com.hwd.gmall.oauth.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 网络安全配置类
 *
 * @author 黄伟东/Victor
 * @date 2022/5/4 17:07
 */
@Configuration
@EnableWebSecurity
@Order(-1)
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 忽略安全拦截的URL
     *
     * @param web WebSecurity
     */
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/user/login", "/api/user/logout");
    }

    /**
     * 创建授权管理认证对象
     *
     * @return org.springframework.security.authentication.AuthenticationManager
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 采用BCryptPasswordEncoder对密码进行编码
     *
     * @return org.springframework.security.crypto.password.PasswordEncoder
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * http过滤验证
     *
     * @param http HttpSecurity
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                // 启用Http基本身份验证
                .httpBasic()
                .and()
                // 启用表单身份验证
                .formLogin()
                .and()
                // 限制基于Request请求访问
                .authorizeRequests()
                .anyRequest()
                // 其他请求都需要经过验证
                .authenticated();
    }
}
